# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo_contrib import models as contrib_models

from ..adaptor.factory import WechatAppFactory


class MiniApp(contrib_models.SchemaModel):
    _name = 'wechat.miniapp'

    name = fields.Char(index=True, require=True, string='名称')  # site
    desc = fields.Text(string='描述')

    default = fields.Boolean(
        default=False,
        string='是否为默认小程序/公众号',
        help='只能设置一个小程序实例为默认小程序/公众号',
    )

    settings = fields.One2many(
        'wechat.settings',
        'miniapp_id',
        limit=1,
        string='程序设置',
    )

    _sql_constraints = [
        ('uq_wechat_miniapp_name', 'UNIQUE(name)', 'Duplicated wechat app name')
    ]

    @api.constrains('default')
    def _check_exclusive_default(self):
        apps = self.search([])
        for entry in self:
            if not entry.default:
                continue
            for app in apps:
                if app.default and self.id != app.id:
                    raise ValidationError('Already has an default wechat app')

    @api.constrains('name')
    def _check_name(self):
        if not self.name:
            raise ValidationError('wechat app name cannot be empty')

        apps = self.search([])
        for app in apps:
            if app.name == self.name and app.id != self.id:
                raise ValidationError('Duplicated wechat app name')

    @api.multi
    def get_adaptor(self):
        self.ensure_one()
        if self.default:
            site = None
        else:
            site = self.name
        return WechatAppFactory()[site]
